package com.donar.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * Created by donar on 18/3/2.
 */
public class NioClient {

    Selector selector;
    public void init( String host,
            int port) throws IOException {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        this.selector = Selector.open();
        channel.connect(new InetSocketAddress(host,port));
        channel.register(selector, SelectionKey.OP_CONNECT);
    }
    public void connect() throws IOException {
        while (true){
            selector.select();
            Iterator<SelectionKey> ite = this.selector.selectedKeys().iterator();
            while(ite.hasNext()){
                SelectionKey key = ite.next();
                ite.remove();
                if(key.isConnectable()){
                    SocketChannel channel = (SocketChannel) key.channel();
                    if(channel.isConnectionPending()){
                        channel.finishConnect();
                    }
                    channel.configureBlocking(false);
                    channel.write(ByteBuffer.wrap("hello server".getBytes()));
                    channel.register(this.selector,SelectionKey.OP_READ);
                }else if(key.isReadable()){
                    //和服务端的read方法一样
                    // 服务器可读取消息:得到事件发生的Socket通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    // 创建读取的缓冲区
                    ByteBuffer buffer = ByteBuffer.allocate(512);
                    channel.read(buffer);
                    byte[] data = buffer.array();
                    String msg = new String(data).trim();
                    System.out.println("client reveive：" + msg);
                    ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes("utf-8"));
                    channel.write(outBuffer);// 将消息回送给客户端
                }
            }
        }
    }

    public static void main(String[] args) throws IOException {
        NioClient client = new NioClient();
        client.init("localhost",8888);
        client.connect();
    }
}
